@page "/admin/posts"
@using MyBlogServer.Models
@using MyBlogServer.Services
@inject PostService PostService
@inject NavigationManager Navigation

@layout AdminLayout
@rendermode InteractiveServer

<PageTitle>Admin - Posts</PageTitle>

<AdminRouteTemplate>
    <div class="admin-container">
        <h2>博客文章管理</h2>

        <div class="mb-3">
            <button class="btn btn-primary" @onclick="CreateNewPost">新建文章</button>
        </div>

        <table class="table table-striped">
            <thead>
            <tr>
                <th>标题</th>
                <th>创建时间</th>
                <th>状态</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            @if (_posts != null && _posts.Any())
            {
                @foreach (var post in _posts)
                {
                    <tr>
                        <td>@post.Title</td>
                        <td>@post.CreatedAt.ToString("yyyy-MM-dd HH:mm")</td>
                        <td>@(post.Published ? "已发布" : "草稿")</td>
                        <td>
                            <button class="btn btn-sm btn-outline-primary" @onclick="() => EditPost(post.Id)">编辑
                            </button>
                            <button class="btn btn-sm btn-outline-danger ms-2" @onclick="() => DeletePost(post.Id)">
                                删除
                            </button>
                        </td>
                    </tr>
                }
            }
            else
            {
                <tr>
                    <td colspan="4" class="text-center">暂无文章</td>
                </tr>
            }
            </tbody>
        </table>
    </div>
</AdminRouteTemplate>

@code {
    private IEnumerable<Post> _posts = new List<Post>();

    protected override async Task OnInitializedAsync()
    {
        await LoadPosts();
    }

    private async Task LoadPosts()
    {
        _posts = await PostService.GetAllPostsAsync(true);
        StateHasChanged();
    }

    private void CreateNewPost()
    {
        Console.WriteLine("点击了新建文章按钮");
        Navigation.NavigateTo("/admin/posts/create", forceLoad: true);
    }

    private void EditPost(int id)
    {
        Navigation.NavigateTo($"/admin/posts/edit/{id}", forceLoad: true);
    }

    private async Task DeletePost(int id)
    {
        await PostService.DeletePostAsync(id);
        await LoadPosts();
    }

}